package 第七周;

/*
 * @author  YxinMiracle
 * @date  2022-05-07 17:14
 * @Gitee: https://gitee.com/yxinmiracle
 */

import java.util.HashMap;
import java.util.Map;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}



public class 打家劫舍3 {
    // 0 为不偷 1为偷
    public Map<TreeNode,int[]> map;

    public int rob(TreeNode root) {
        map = new HashMap<>();
        map.put(null,new int[]{0,0});
        dfs(root);
        return Math.max(map.get(root)[0],map.get(root)[1]);
    }

    public void dfs(TreeNode root){
        if (root == null) return;
        map.put(root,new int[2]);
        dfs(root.left);
        dfs(root.right);
        // 不偷 那么子树可以偷也可以不偷
        map.get(root)[0] = Math.max(map.get(root.left)[0],map.get(root.left)[1]) + Math.max(map.get(root.right)[0],map.get(root.right)[1]) + root.val;
        // 子树就不可以偷了
        map.get(root)[1] = map.get(root.left)[0] + map.get(root.right)[0];
    }

}
